package com.example.native_activity;

import android.Manifest;
import android.app.NativeActivity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PackageManagerCompat;

import java.util.concurrent.LinkedBlockingQueue;

public class MainActivity extends NativeActivity {

    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 123;
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1;

    private void requestStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestStoragePermission();

        String[] permissions={
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        // 检查是否已授予读取外部存储权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果权限未授予，请求权限
            ActivityCompat.requestPermissions(this,
                    permissions,
                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        }
    }

    void showSoftInput()
    {
        InputMethodManager inputMethodManager= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(this.getWindow().getDecorView(),0);
    }
    void hideSoftInput()
    {
        InputMethodManager inputMethodManager= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(),0);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event)
    {
        if(event.getAction()==KeyEvent.ACTION_DOWN)
        {
            unicodeCharacterQueue.offer(event.getUnicodeChar());
        }
        return super.dispatchKeyEvent(event);
    }

    LinkedBlockingQueue<Integer> unicodeCharacterQueue = new LinkedBlockingQueue<Integer>();
    int pollUnicodeChar()
    {
        Integer r=unicodeCharacterQueue.poll();
        if(r==null)
        {
            return 0;
        }else {
            return r;
        }
    }


}
